package com.mmy.fta.usercenter.rest;

import com.alibaba.fastjson.JSONObject;
import com.mmy.fta.usercenter.config.WeChatConfig;
import com.mmy.fta.usercenter.dto.DriverDTO;
import com.mmy.fta.usercenter.dto.DriverLicenseDTO;
import com.mmy.fta.usercenter.dto.DrivingLicenseDTO;
import com.mmy.fta.usercenter.dto.UserDTO;
import com.mmy.fta.usercenter.model.AppletsLoginModel;
import com.mmy.fta.usercenter.request.DriverInfoRequest;
import com.mmy.fta.usercenter.request.DriverLicenseRequest;
import com.mmy.fta.usercenter.request.DrivingLicenseRequest;
import com.mmy.fta.usercenter.request.VerifyCodeRequest;
import com.mmy.fta.usercenter.request.VerifyRequest;
import com.mmy.fta.usercenter.service.impl.UserServiceImpl;
import com.ymm.common.rpc.YmmResult;
import com.ymm.common.web.YmmResponse;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import java.util.HashMap;
import java.util.Map;

/**
 * @apiNote 微信登录接口
 * @author qingyu.meng
 * @date 2021年10月19日 11:28 上午
 * @Description
 */
@RestController
@RequestMapping("/auth")
@Slf4j
public class WeChatController {

    @Autowired
    RestTemplate restTemplate;

    @Autowired
    WeChatConfig weChatConfig;

    @Autowired
    UserServiceImpl userService;

    private static final Logger LOGGER = LoggerFactory.getLogger(WeChatController.class);


    /**
     * 货主用户登录
     * @param appletsLoginModel
     * @return
     */
    @PostMapping(value = "/login/applets")
    public YmmResponse<UserDTO> shipperLogin(@RequestBody AppletsLoginModel appletsLoginModel) {
        log.info("请求参数为：" + appletsLoginModel.getCode());
        String url = "https://api.weixin.qq.com/sns/jscode2session?appid={appid}&secret={secret}&js_code={code}&grant_type=authorization_code";
        Map<String, String> requestMap = new HashMap<>( );
        requestMap.put("appid", weChatConfig.getAppid());
        requestMap.put("secret", weChatConfig.getSecret());
        requestMap.put("code", appletsLoginModel.getCode( ));
        ResponseEntity<String> responseEntity = restTemplate.getForEntity(url, String.class, requestMap);
        JSONObject jsonObject = JSONObject.parseObject(responseEntity.getBody());
        System.out.println(">>>>>>>>>>>JSONObject is: " + jsonObject);
        String openId = jsonObject.getString("openid");
        String session_key = jsonObject.getString("session_key");
        // String token = session_key + openId;
        YmmResult<UserDTO> loginResult = userService.login(openId);
        if (loginResult.isSuccess()){
            UserDTO userDTO = loginResult.getData();
            userDTO.setToken(openId);
            log.info(userDTO.toString());
            return YmmResponse.succResponse(userDTO);
        }
        return YmmResponse.failResponse(000,"登录失败");
    }

    /**
     * 司机用户登录
     * @param appletsLoginModel
     * @return
     */
    @PostMapping(value = "/login-driver/applets")
    public YmmResponse<UserDTO> driverLogin(@RequestBody AppletsLoginModel appletsLoginModel) {
        log.info("请求参数为：" + appletsLoginModel.getCode());
        String url = "https://api.weixin.qq.com/sns/jscode2session?appid={appid}&secret={secret}&js_code={code}&grant_type=authorization_code";
        Map<String, String> requestMap = new HashMap<>();
        requestMap.put("appid", "wxd9ebc1a9cd409b79");
        requestMap.put("secret", "316fb33c117238e3b0afba817eb2c175");
        requestMap.put("code", appletsLoginModel.getCode());
        ResponseEntity<String> responseEntity = restTemplate.getForEntity(url, String.class, requestMap);
        JSONObject jsonObject = JSONObject.parseObject(responseEntity.getBody());
        System.out.println(">>>>>>>>>>>JSONObject is: " + jsonObject);
        String openId = jsonObject.getString("openid");
        String session_key = jsonObject.getString("session_key");
        // String token = session_key + openId;
        YmmResult<UserDTO> loginResult = userService.login(openId);
        if (loginResult.isSuccess()){
            UserDTO userDTO = loginResult.getData();
            userDTO.setToken(openId);
            log.info(userDTO.toString());
            return YmmResponse.succResponse(userDTO);
        }
        return YmmResponse.failResponse(000,"登录失败");
    }

    /**
     * 用户实名认证
     * @param verifyRequest
     * @return
     */
    @PostMapping(value = "/verify")
    public YmmResponse<UserDTO> verify(@RequestBody VerifyRequest verifyRequest){
        LOGGER.info("WeChatController:verify 用户实名认证,request is: " , JSONObject.toJSONString(verifyRequest));
        String token = verifyRequest.getToken();
        try {
            YmmResult<UserDTO> verify = userService.verify(verifyRequest);
            UserDTO data = verify.getData();
            return YmmResponse.succResponse(data);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return YmmResponse.failResponse(000,"实名认证失败");
    }

    /**
     * 货主认证OCR识别
     * @return
     */
    @PostMapping(value = "/ocr")
    public YmmResponse<UserDTO> OCRMessage(){
        LOGGER.info("WeChatController:OCRMessage OCR识别认证");
        YmmResult<UserDTO> userDTOYmmResult = userService.OCRMessage();
        UserDTO data = userDTOYmmResult.getData();
        return YmmResponse.succResponse(data);
    }

    /**
     * 行驶证OCR识别
     * @return
     */
    @PostMapping(value = "/driving-license/ocr")
    public YmmResponse<DrivingLicenseDTO> drivingLicenseOCR(){
        LOGGER.info(">>>>>>>>>>WeChatController:drivingLicenseOCR<<<<<<<<<");
        YmmResult<DrivingLicenseDTO> vehicleDTOYmmResult = userService.drivingLicenseOCR();
        DrivingLicenseDTO data = vehicleDTOYmmResult.getData();
        return YmmResponse.succResponse(data);
    }

    /**
     * 驾驶证OCR识别
     * @return
     */
    @PostMapping(value = "/driver-license/ocr")
    public YmmResponse<DriverLicenseDTO> driverLicenseOCR(){
        LOGGER.info(">>>>>>>>>>WeChatController:driverLicenseOCR<<<<<<<<<");
        YmmResult<DriverLicenseDTO> driverLicenseDTOYmmResult = userService.driverLicenseOCR();
        DriverLicenseDTO data = driverLicenseDTOYmmResult.getData();
        return YmmResponse.succResponse(data);
    }



    /**
     * 发送验证码
     * @param request
     * @return
     */
    @PostMapping(value = "/sendVerifyCode")
    public YmmResponse sendVerifyCode(@RequestBody VerifyCodeRequest request){
        userService.sendVerifyCode(request.getPhoneNumber());
        return YmmResponse.succResponse();
    }

    /**
     * 验证验证码
     * @param request
     * @return
     */
    @PostMapping(value = "/verifyCode")
    public YmmResponse verifyCode(@RequestBody VerifyCodeRequest request){
        YmmResult ymmResult = userService.verifyCode(request.getPhoneNumber(), request.getVerifyCode());
        if (ymmResult.isSuccess()){
            return YmmResponse.succResponse();
        }
        return YmmResponse.failResponse(000,ymmResult.getErrorMsg());
    }

    /**
     * 用户行驶证认证
     * @param request
     * @return
     */
    @PostMapping(value = "/driving-license/verify")
    public YmmResponse verifyDrivingLicense(@RequestBody DrivingLicenseRequest request){
        LOGGER.info("WeChatController:verifyDrivingLicense 用户行驶证认证,request is: " + request);
        String token = request.getToken();
        DrivingLicenseDTO drivingLicenseDTO = new DrivingLicenseDTO();
        BeanUtils.copyProperties(request,drivingLicenseDTO);
        YmmResult ymmResult = userService.saveDrivingLicenseInfo(drivingLicenseDTO, request.getToken());
        if (ymmResult.isSuccess()){
            return YmmResponse.succResponse();
        }
        return YmmResponse.failResponse(000,"行驶证信息认证失败");
    }

    /**
     * 用户驾驶证认证
     * @param request
     * @return
     */
    @PostMapping(value = "/driver-license/verify")
    public YmmResponse verifyDriverLicense(@RequestBody DriverLicenseRequest request){
        LOGGER.info("WeChatController:verifyDriverLicense 用户驾驶证认证,request is: " + request);
        String token = request.getToken();
        DriverLicenseDTO driverLicenseDTO = new DriverLicenseDTO();
        BeanUtils.copyProperties(request,driverLicenseDTO);
        YmmResult ymmResult = userService.saveDriverLicenseInfo(driverLicenseDTO, request.getToken());
        if (ymmResult.isSuccess()){
            return YmmResponse.succResponse();
        }
        return YmmResponse.failResponse(000,"驾驶证信息认证失败");
    }

    /**
     * 保存司机信息
     * @param request
     * @return
     */
    @PostMapping(value = "/save/driver-info")
    public YmmResponse saveDriverInfo(@RequestBody DriverInfoRequest request){
        LOGGER.info("WeChatController:saveDriverInfo 保存司机信息,request is: " + request);
        try{
            String token = request.getToken();
            DriverDTO driverDTO = new DriverDTO();
            BeanUtils.copyProperties(request,driverDTO);
            YmmResult ymmResult = userService.saveDriverInfo(driverDTO, token);
            if (ymmResult.isSuccess()){
                return YmmResponse.succResponse();
            }

            return YmmResponse.failResponse(000,ymmResult.getErrorMsg());
        } catch (Exception e) {
            log.info("[xxxx] e:{}",e.getMessage());
            return YmmResponse.failResponse(0,"error");
        }
    }

}
